where 泛型類型條件約束


Posted by nimblefrog on 2021-01-04

泛型定義中的 where 子句(where T)指定型別T的條件約束,以用來作為泛型型別、方法、委派或本機函式中型別參數的引數。
條件約束可以指定

  1. 介面
    public class AGenericClass<T> where T : IComparable<T> { }
    
  2. 基類
    public class UsingEnum<T> where T : System.Enum { }
    public class UsingDelegate<T> where T : System.Delegate { }
    public class Multicaster<T> where T : System.MulticastDelegate { }
    
  3. 要求泛型型別作為參考(class)、值(notnullstruct)或非受控型別(unmanaged )
  4. new 條件約束: 指定泛型類別宣告中的型別引數都必須有公用無參數建構函式,若要使用 new 條件約束,型別不能為抽象
    class ItemFactory<T> where T : new()
    {
         public T GetNewItem()
         {
             return new T();
         }
    }
    

where (泛型類型條件約束) (C# 參考)
new 條件約束 (C# 參考)










Related Posts

[Preparation for Interview Basic 1] DOM Element

[Preparation for Interview Basic 1] DOM Element

【Day07】總複習!摻在一起做成...

【Day07】總複習!摻在一起做成...

曾經的前端  library 霸主 :  jQuery

曾經的前端 library 霸主 : jQuery


Comments